package com.healthcare.cameraview.ws;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class QwenHttpClient {
    private static final Logger logger = LoggerFactory.getLogger(QwenHttpClient.class);
    
    // 使用KeyAPI的通义千问多模态API端点
    private static final String QWEN_API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation";
    private static final String MODEL_NAME = "qwen-vl-plus"; // 使用qwen-vl-plus模型
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private final String apiKey;
    private final HttpClient httpClient;
    private volatile boolean connected = true;

    public QwenHttpClient(String apiKey) {
        this.apiKey = apiKey;
        this.httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();
        logger.info("通义千问HTTP客户端初始化成功 - 模型: {}", MODEL_NAME);
    }

    public boolean isOpen() {
        return connected;
    }

    public void connectBlocking() throws InterruptedException {
        // HTTP API不需要连接，直接返回
        logger.info("通义千问HTTP API客户端已就绪");
    }

    /**
     * 分析图像内容
     * @param base64Image Base64编码的图像
     * @param prompt 分析提示词
     */
    public void analyzeImage(String base64Image, String prompt) {
        CompletableFuture.runAsync(() -> {
            try {
                // 构建多模态请求体
                Map<String, Object> request = buildMultimodalRequest(base64Image, prompt);
                
                String requestBody = objectMapper.writeValueAsString(request);
                logger.debug("发送AI分析请求，提示词: {}", prompt);

                HttpRequest httpRequest = HttpRequest.newBuilder()
                    .uri(URI.create(QWEN_API_URL))
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .timeout(Duration.ofSeconds(30))
                    .build();

                HttpResponse<String> response = httpClient.send(httpRequest, 
                    HttpResponse.BodyHandlers.ofString());

                handleResponse(response);

            } catch (Exception e) {
                logger.error("发送AI分析请求失败: {}", e.getMessage(), e);
                broadcastError("AI分析请求失败: " + e.getMessage());
            }
        });
    }

    private Map<String, Object> buildMultimodalRequest(String base64Image, String prompt) {
        Map<String, Object> request = new HashMap<>();
        request.put("model", MODEL_NAME);
        
        // 构建输入消息
        Map<String, Object> input = new HashMap<>();
        List<Map<String, Object>> messages = new ArrayList<>();
        
        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");
        
        // 构建多模态内容
        List<Map<String, Object>> content = new ArrayList<>();
        
        // 添加文本提示
        Map<String, Object> textContent = new HashMap<>();
        textContent.put("type", "text");
        textContent.put("text", prompt);
        content.add(textContent);
          // 添加图像内容
        Map<String, Object> imageContent = new HashMap<>();
        imageContent.put("type", "image");
        imageContent.put("image", "data:image/jpeg;base64," + base64Image);
        content.add(imageContent);
        
        message.put("content", content);
        messages.add(message);
        
        input.put("messages", messages);
        request.put("input", input);
        
        // 设置参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("result_format", "message");
        parameters.put("max_tokens", 1500);
        parameters.put("temperature", 0.7);
        request.put("parameters", parameters);
        
        return request;
    }

    private void handleResponse(HttpResponse<String> response) {
        try {
            if (response.statusCode() == 200) {
                handleSuccessResponse(response.body());
            } else {
                logger.error("HTTP请求失败: status={}, body={}", response.statusCode(), response.body());
                broadcastError("请求失败: HTTP " + response.statusCode());
            }
        } catch (Exception e) {
            logger.error("处理响应失败: {}", e.getMessage(), e);
            broadcastError("响应处理失败: " + e.getMessage());
        }
    }
    
    private void handleSuccessResponse(String responseBody) {
        try {
            logger.info("收到通义千问响应: {}", responseBody);
            @SuppressWarnings("unchecked")
            Map<String, Object> response = objectMapper.readValue(responseBody, Map.class);
            
            // 处理成功响应
            if (response.containsKey("output")) {
                @SuppressWarnings("unchecked")
                Map<String, Object> output = (Map<String, Object>) response.get("output");
                
                if (output.containsKey("choices")) {
                    @SuppressWarnings("unchecked")
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) output.get("choices");
                      if (!choices.isEmpty()) {
                        Map<String, Object> choice = choices.get(0);
                        @SuppressWarnings("unchecked")
                        Map<String, Object> messageObj = (Map<String, Object>) choice.get("message");
                        
                        // 处理content数组格式
                        String content = "";
                        Object contentObj = messageObj.get("content");
                        if (contentObj instanceof List) {
                            @SuppressWarnings("unchecked")
                            List<Map<String, Object>> contentList = (List<Map<String, Object>>) contentObj;
                            if (!contentList.isEmpty()) {
                                Map<String, Object> textObj = contentList.get(0);
                                content = (String) textObj.get("text");
                            }
                        } else if (contentObj instanceof String) {
                            content = (String) contentObj;
                        }                        // 打印AI分析结果到控制台
                        logger.info("🤖 AI分析结果: {}", content);
                        
                        // 清理markdown代码块包装的JSON内容
                        String cleanContent = cleanMarkdownJson(content);
                        logger.info("🧹 清理后的内容: {}", cleanContent);
                        
                        // 尝试解析JSON格式的异常行为预测结果
                        try {
                            @SuppressWarnings("unchecked")
                            Map<String, Object> predictionData = objectMapper.readValue(cleanContent, Map.class);
                            
                            // 验证必需字段
                            if (predictionData.containsKey("level") && 
                                predictionData.containsKey("reason") && 
                                predictionData.containsKey("predict")) {
                                
                                // 发送结构化的异常行为预测结果到前端
                                String resultPayload = String.format(
                                    "{\"type\":\"analysis\",\"level\":%s,\"reason\":\"%s\",\"predict\":\"%s\",\"timestamp\":%d}", 
                                    predictionData.get("level"),
                                    String.valueOf(predictionData.get("reason")).replace("\"", "\\\""),
                                    String.valueOf(predictionData.get("predict")).replace("\"", "\\\""),
                                    System.currentTimeMillis()
                                );
                                VideoWebSocketHandler.broadcast(resultPayload);
                                logger.info("📊 异常行为预测: 等级{}, 原因: {}, 预测: {}", 
                                    predictionData.get("level"), 
                                    predictionData.get("reason"), 
                                    predictionData.get("predict"));
                            } else {
                                logger.warn("AI返回的JSON缺少必需字段，发送原始内容");
                                sendFallbackResult(content);
                            }
                        } catch (Exception parseException) {
                            logger.warn("解析AI返回的JSON失败: {}, 发送原始内容", parseException.getMessage());
                            sendFallbackResult(content);
                        }
                    }
                }
            } 
            // 处理错误响应
            else if (response.containsKey("code")) {
                String code = (String) response.get("code");
                String errorMessage = (String) response.get("message");
                logger.error("通义千问返回错误: code={}, message={}", code, errorMessage);
                broadcastError("AI分析失败: " + errorMessage);
            }
        } catch (Exception e) {
            logger.error("处理通义千问响应失败: {}", e.getMessage(), e);
            broadcastError("响应解析失败");
        }
    }      private void broadcastError(String errorMessage) {
        // 只打印错误到控制台，不发送到WebSocket
        logger.error("🚨 AI分析错误: {}", errorMessage);
    }
      private void sendFallbackResult(String content) {
        // 当无法解析JSON时，发送原始内容作为fallback
        String resultPayload = String.format(
            "{\"type\":\"analysis\",\"result\":\"%s\",\"timestamp\":%d}", 
            content.replace("\"", "\\\"").replace("\n", "\\n"), 
            System.currentTimeMillis()
        );
        VideoWebSocketHandler.broadcast(resultPayload);
    }
    
    /**
     * 清理AI响应中的markdown代码块包装
     * @param content 原始AI响应内容
     * @return 清理后的JSON字符串
     */
    private String cleanMarkdownJson(String content) {
        if (content == null) {
            return "";
        }
        
        // 移除markdown代码块标记
        String cleaned = content.trim();
        
        // 移除开头的```json 或 ```
        if (cleaned.startsWith("```json")) {
            cleaned = cleaned.substring("```json".length()).trim();
        } else if (cleaned.startsWith("```")) {
            cleaned = cleaned.substring("```".length()).trim();
        }
        
        // 移除结尾的```
        if (cleaned.endsWith("```")) {
            cleaned = cleaned.substring(0, cleaned.length() - 3).trim();
        }
        
        return cleaned;
    }
}
